$(function () {
  var doneConfirm = new Confirm({
    body: "Are you confirm to save?"
  })

  const csrf = $('input[name="csrfmiddlewaretoken"]').val()
  function getCheckUser(username_b64, state) {
    data = new FormData()
    data.append("username", username_b64)
    data.append("check_state", state)
    return axios.post(getCheckUser_url, data,
      {
        headers: {
          "X-CSRFTOKEN": csrf
        }
      })

  }

  function reviseForm(username_b64, state) {
    data = new FormData()
    data.append("username", username_b64)
    data.append("eform_id", eform_id)

    return axios.post(getResetEndorsed_url, data,
      {
        headers: {
          "X-CSRFTOKEN": csrf
        }
      })

  }


  readOnly = (revise == 'True') ? false : true
  Formio.icons = 'fontawesome';
  Formio.createForm(document.getElementById('formio'),
    dataJson,
    {
      readOnly
      // renderMode: 'html'
    }
  ).then(function (form) {

    let deleteScan = new GnsScan(
      content => {
        getCheckUser(content, 'delete').then(response => {
          data = response.data
          if (!data.ack) {
            deleteScan.setAlert(data.err)
            return
          }

          setForm('delete')
          $('#eform').trigger('submit')

          deleteScan.close()
          // setUI(data.username)
          // setUser_id(data.user_id)

        })
      }, title = 'Scan Staff QRCode to DELETE Form'
    )

    let resetScan = new GnsScan(
      content => {
        getCheckUser(content, 'reset').then(response => {
          data = response.data
          if (!data.ack) {
            resetScan.setAlert(data.err)
            return
          }

          setForm('reset')
          $('#eform').trigger('submit')

          resetScan.close()
          // setUI(data.username)
          // setUser_id(data.user_id)

        })
      }, title = 'Scan Staff QRCode to RESET Form'
    )

    let reviseScan = new GnsScan(
      content => {
        reviseForm(content, 'reset').then(response => {
          data = response.data
          if (!data.ack) {
            reviseScan.setAlert(data.err)
            return
          } else {
            setForm('revise')
            $('#eform').submit()
          }
          reviseScan.close()
        })
      }, title = 'Scan Staff QRCode to Revise Form'
    )

    $('#btn-revise').on('click', function (e) {
      reviseScan.instascan()
    })

    $('#check_as_other').on('click', function () {
      $('#choose-check-user-modal').modal('hide')
      $('#scan_modal').modal('show')
      instascan()
    })

    $('#final_check_as_other').on('click', function () {
      $("#eform").trigger('submit')
    })

    // var deleteConfirm = new Confirm({
    //   body: "Type <strong>\"DELETE\"</strong> to delete the form.",
    //   type: 'prompt'
    // })

    // var resetConfirm = new Confirm({
    //   body: "Type <strong>\"RESET\"</strong> to reset the form state.",
    //   type: 'prompt'
    // })

    console.log(data)
    form.submission = {
      data: data
    }
    // console.log(form._data)
    $('input[name="overall_test_result_radio"]').on('change', function () {
      $('#form-otr').val($(this).val())
    })

    $('#btn-reset').on('click', function (e) {
      resetScan.instascan()
      // resetConfirm.show((yes, p_value) => {
      //   if (yes && p_value == 'RESET') {
      //     setForm('reset')
      //     $('#eform').submit()
      //     console.log('yes')
      //   }
      // })
    })

    $('#btn-delete').on('click', function (e) {
      deleteScan.instascan()
      // deleteConfirm.show((yes, p) => {
      //   if (yes && p == "DELETE") {
      //     setForm('delete')
      //     $('#eform').trigger('submit')
      //   }
      // })
    })

    $('.check-btn').on('click', function (e) {
      var action = $(this).val()
      setForm(action)
      $('#choose-check-user-modal').modal('show')
      // $('#eform').trigger('submit')
    })

    $('.save-btn').on('click', function (e) {
      var action = $(this).val()
      setForm(action)
      setFormData()
      doneConfirm.show(() => {
        //CHECK REMARK FIELD
        var remark_ok = validateForm();
        // check formio
        if (form.checkValidity(null, true) == false || remark_ok == false) {
          // scroll to invalid
          invalid = $('.is-invalid')[0]
          if (invalid) {
            invalid.focus()
          }
          return
        }

        let fm = document.getElementById('eform')

        if (!fm.checkValidity()) {
          setTimeout(_ => fm.reportValidity(), 100)
          return
        }
        // $('#dataAction').val(action)
        $('#overall_test_result').val($('input[name="overall_test_result_radio"]:checked').val())
        $('#eform').trigger('submit')

      }, (bo) => {
        return bo
      })
    })

    $('#check-current-user').on('click', function () {
      setForm($(this).val())
      $("#eform").trigger('submit')
    })



    function setForm(action) {
      $('#eform-action').val(action)
    }

    function setFormData() {
      $('#eform-data').val(JSON.stringify(form._data))
    }

  });

})